package art.java.concurrency.chapter04;

import java.util.concurrent.TimeUnit;

/**
 * @author <a href="eric_zheng@lanzuo.com.cn">eric</a>
 * @version 1.0.0
 * Description: 线程中断
 */
public class Interrupted {

    public static void main(String[] args) throws InterruptedException {
        // sleep 线程不停的睡眠
        Thread sleepThread = new Thread(new SleepRunner(), "sleepRunner");
        sleepThread.setDaemon(true);
        // busy线程不停的运行
        Thread busyThread = new Thread(new BusyRunner(), "busyRunner");
        busyThread.setDaemon(true);

        sleepThread.start();
        busyThread.start();

        // 让两个线程充分运行
        TimeUnit.SECONDS.sleep(5);

        sleepThread.interrupt();
        busyThread.interrupt();

        System.out.println("sleep Thread interrupted is " + sleepThread.isInterrupted());
        System.out.println("busy Thread interrupted is " + busyThread.isInterrupted());

        // 防止两个线程立刻退出
        SleepUtils.second(2);

    }

    static class SleepRunner implements Runnable {

        @Override
        public void run() {
            while (true) {
                // sleep 是会抛出interrupt异常
                SleepUtils.second(10);
            }
        }
    }

    static class BusyRunner implements Runnable {

        @Override
        public void run() {
            while (true) {

            }
        }
    }
}

/**
 * sleep Thread interrupted is false
 * busy Thread interrupted is true
 * java.lang.InterruptedException: sleep interrupted
 * at java.lang.Thread.sleep(Native Method)
 * at java.lang.Thread.sleep(Thread.java:340)
 * at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
 * at art.java.concurrency.chapter04.SleepUtils.second(SleepUtils.java:8)
 * at art.java.concurrency.chapter04.Interrupted$SleepRunner.run(Interrupted.java:43)
 * at java.lang.Thread.run(Thread.java:748)
 */
